﻿/*jslint */
/*global openDatabase: true, $: true */
"use strict";
//
console.log = function () { }
var Page_Contact = (function () {
   
    // Read a page's GET URL variables and return them as an associative array.
    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

    //find the Paging in the URL
    function getURLNextPage() {
        /* /Page/2/ */
        var vars = [], hash;
        var pageNum=1;
        var hashes = window.location.href.slice(window.location.href.indexOf('#') + 2).split('/');
      
        //console.log('current Paging: ' + hashes[1]);
        if (hashes[1]) {
            pageNum = hashes[1];
        }
        return pageNum;
    }

    function errorHandler(transaction, error) {
        console.log('Oops. Error was ' + error.message + ' (Code ' + error.code + ')');
        return true;
    }

    function DateDiff(date1, date2) {
        console.log("entering: DateDiff");
        console.log("date1: " + date1);
        console.log("date2: " + date2);

        return date1.getTime() - date2.getTime();
    }

    /*calculate_LastContactedInfo*/
    function calculate_LastContactedInfo(oTimeAgo) {
        console.log("entering: calculate_LastContactedInfo");

        var secondsInAYear = 31556000;      //seconds in a year
        var secondsInAMonth = 2630000;      //seconds in a month
        var secondsInAWeek = 604800;        //seconds in a week
        var secondsInADay = 86400;           //seconds in a day
        var secondsInAnHour = 3600;           //seconds in an hour
        var secondsInAMinute = 60;           //seconds in a minutes

        console.log(oTimeAgo.lastContactedDate);

        //Find the Difference in Seconds
        var d = new Date();
        var d2 = Date.parse(oTimeAgo.lastContactedDate);                     //converts it to milliseconds - as if get..time

        var _contactedSinceInSeconds = (d.getTime() - d2) / 1000;   //in milliseconds

        var result = '';
        if (_contactedSinceInSeconds >= secondsInAYear){
            //Do we have enough for years?
            result += 'More Than ' + parseInt((_contactedSinceInSeconds / secondsInAYear),10) + ' Year(s) Ago';
            oTimeAgo.flagColor = "status_off";
        }
        else if (_contactedSinceInSeconds >= secondsInAMonth){
            //how many months exactly
            result += parseInt((_contactedSinceInSeconds / secondsInAMonth), 10) + ' Month(s) Ago';
            oTimeAgo.flagColor = "status_off";
        }
        else if (_contactedSinceInSeconds >= secondsInAWeek) {
            //how many weeks exactly
            result += parseInt((_contactedSinceInSeconds / secondsInAWeek),10) + ' Week(s) Ago';
            oTimeAgo.flagColor = "status_away";
        }
        else if ( _contactedSinceInSeconds > secondsInADay){
            //how many days exactly
            var howManyDays = parseInt((_contactedSinceInSeconds / secondsInADay),10);
            result += howManyDays + ' Day(s) Ago';

            if (howManyDays > 3){
                oTimeAgo.flagColor = "status_available"; //green
            }
            else {
                //TODO:make it a setting
                //more than 3 days
                oTimeAgo.flagColor = "status_away";      //yellow
            }
        }
        else if (_contactedSinceInSeconds > secondsInAnHour) {
            //how many hours exactly
            result += parseInt((_contactedSinceInSeconds / secondsInAnHour),10) + ' Hour(s) Ago';
            oTimeAgo.flagColor = "status_available";
        }
        else if (_contactedSinceInSeconds > secondsInAMinute) {
            //how many minutes exactly
            result += parseInt((_contactedSinceInSeconds / secondsInAMinute),10) + ' Minute(s) Ago';
            oTimeAgo.flagColor = "status_available";
        }
        else if (_contactedSinceInSeconds > 1) {
            //how many minutes exactly
            result += parseInt(_contactedSinceInSeconds,10) + ' Second(s) Ago';
            oTimeAgo.flagColor = "status_available";
        }

        //return the last contacted text
        oTimeAgo.lastContactedInfo = result;
        return result;
    }

    /*calculate_TimeSinceLastContacted*/
    function calculate_TimeSinceLastContacted(singleContact, oTimeAgo) {

        //get the lastcontacted from the contact infor
        var _lastContactedDate;
        var _dateCreated = singleContact.DateCreated;

        //Set the last Contacted
        _lastContactedDate = _dateCreated;      //we should
        if (singleContact.DateLastContacted)
            _lastContactedDate = singleContact.DateLastContacted;
    
        //Get the last Contacted Info Text
        oTimeAgo.lastContactedDate = _lastContactedDate
        var _lastContactedInfo = calculate_LastContactedInfo(oTimeAgo);

        //oTimeAgo.lastContactedInfo = _lastContactedInfo;
        //oTimeAgo.flagColor = flagColor;

        return oTimeAgo;
    }


    //send to preset
    function sendToPreset() {

        //dataService.dropTable(appGlobalVars.table_UserCred());
        //dataService.dropTable(appGlobalVars.table_Contacts());
        //dataService.dropTable(appGlobalVars.table_ContactInfos());

        //send to the preset page, for full reset of the data
        window.location = "presets.html?fullreset=1";
    }




    function callback_ListContactsFromStorage_Success(contacts) {

        console.log("entering: callback_ListContactsFromStorage_Success");

        //if we could not identify any contacts, let's send it to the preset for table restoration
        if (contacts.length == 0) {
            sendToPreset();
            return false;
        }

        for (var i = 0; i < contacts.length; i++) {
            var singleContact = contacts[i];

            /********************************/
            //some weird object
            /********************************/
            var oDisplay = new Object();
            oDisplay.lastContactedDate = '';
            oDisplay.lastContactedInfo = '';
            oDisplay.flagColor = '';
            /********************************/

            //handle the display name
            oDisplay.displayName =singleContact.displayName; 
            if (!singleContact.displayName)
            {
                oDisplay.displayName = 'No Name';
            }

            //handle the picture
            oDisplay.picturePath = singleContact.picturePath;
            if (!singleContact.picturePath) {
                //avatar picture
                oDisplay.picturePath = 'images/live/avatar_noPic.png';
            }
            console.log('picture I will use: ' + oDisplay.picturePath);

            //perform the calculation of last time contacted
            calculate_TimeSinceLastContacted(singleContact, oDisplay);       //oDisplay, by reference

            //populate the contact list
            var itemToAdd = '<li class="contactitem">'
								+ '<a class="cdetails" href="contactDetails.html?ref=' + singleContact.Ukey + '" style="margin-top: -8px">'
										+ '<img src="' + oDisplay.picturePath + '" alt="" />'
										+ '<span class="contactName">'
											+ '<strong>' + oDisplay.displayName + '<span></span></strong>'
											+ '<i>' + oDisplay.lastContactedInfo + '</i>'
										+ '</span>'
										+ '<span class="' + oDisplay.flagColor + '"> </span>'
										+ '<span class="clear"></span>'
								+ '</a>'
							+ '</li>';

            $("#contactList").append(itemToAdd);
        }

    };

    // onError: Failed to get the contacts
    //
    function callback_ListContactsFromStorage_Error(contactError) {
        console.log('entering: callback_ListContactsFromStorage_Error');
        console.log('error: ' + contactError);
        alert('error: ' + contactError.message);
        $("#contactsContainer").html("ERROR.unable to load contacts...");
    }

    function UpdateQueryOpts_totalReturned(totalReturned)
    {
        //build the query          
        var oQueryOpts = new Object()

       // alert('hell yeah');
        //get the object actually from the page
        if (localStorage) {
            if (!localStorage.queryOpts) {
                //first time

                oQueryOpts.currentLimit = 20;
                oQueryOpts.currentOffset = 20;
                oQueryOpts.currentPage = 1;
                oQueryOpts.currentFilter = '';
                oQueryOpts.currentSort = 'displayName';
                oQueryOpts.currentSortDirection = '';
                oQueryOpts.totalRecords = totalReturned;
                //// -- end of the options //
            }
            else {

                //get the object from local storage
                var retrievedString = localStorage.getItem('queryOpts');
                oQueryOpts = JSON.parse(retrievedString);
                oQueryOpts.totalRecords = totalReturned;
            }

            //write it back
            //store it in local storage
            localStorage.setItem('queryOpts', JSON.stringify(oQueryOpts));
        }
        else {
            //TODO:this device is not supported, we need local storage on the machine anyway!
        }
    }

    //
    function checkFirstTime_ForRedirection() {
        //have we been here before?      
        //TODO: Consolidate this
        //check the tables
        dataService.isTableExists( appGlobalVars.table_UserCred(),
                                        function tableExistsCallBack(foundIt, error) {
                                            if (!foundIt) {
                                                sendToPreset();
                                                return false;
                                            }
                                        }

            );

        return true;
    }



    /************************************************************************/
    /*      BEGIN EXPOSED FUNCTIONS                                         */
    /************************************************************************/
    return {

        //********************************************************************/
        //Init function
        //********************************************************************/
        fn_init: function () {
           
            console.log('contact page fn_init');

            //start the database
            dataService.startDatabase();

            //console.log('contact page fn_init');

            ////show message
            $("#lastPostsLoader").css("display", "inline");

            ////get the lists
            this.fn_listContacts_fromLocalStorage();

            //hide message
            $("#lastPostsLoader").css("display", "none");

        },

        /* GET CONTACTS COUNT FROM LOCAL STORAGE*/
        fn_getTotalContacts_fromLocalStorage: function () {
            //start the database
            dataService.startDatabase();

            var totalReturned=0;

            return dataService.getContacts_Count_FromLocalStorage(
                function getTotal(totalReturned) {
                    UpdateQueryOpts_totalReturned(totalReturned);
                }
             );
        },

       

        /* LIST CONTACTS FROM LOCAL STORAGE*/
        fn_listContacts_fromLocalStorage: function () {
            console.log('fn_listContacts_fromLocalStorage');

            //build the query          
            var oQueryOpts = new Object()

            //get the object actually from the page
            if (localStorage) {
                if (!localStorage.queryOpts) {
                    //first time

                    oQueryOpts.currentLimit = 20;
                    oQueryOpts.currentOffset = 20;
                    oQueryOpts.currentPage = 1;
                    oQueryOpts.currentFilter = '';
                    oQueryOpts.currentSort = 'displayName';
                    oQueryOpts.currentSortDirection = '';
                    oQueryOpts.totalRecords = 0;
                    //// -- end of the options //
                }
                else {

                    //get the object from local storage
                    var retrievedString = localStorage.getItem('queryOpts');
                    oQueryOpts = JSON.parse(retrievedString);
                }
            }
            else {
                //TODO:this device is not supported, we need local storage on the machine anyway!
            }


            //CheckFirstTime for redirection
            if (checkFirstTime_ForRedirection())
            {
                //get the contacts from our local table
                dataService.getContacts_FromLocalStorage(oQueryOpts, callback_ListContactsFromStorage_Success,
                                              callback_ListContactsFromStorage_Error);
           }   

     },

        /*************************************************************/
//        fn_BuildQueryObject: function (oQueryOpts) {
//        console.log('entering BuildQueryObject');

//    //var url = getUrlVars();
//    //var currentPage = getURLNextPage();
//    //var oQueryOpts = new Object();

//    //get the object actually from the page
//    if (localStorage) {
//        if (!localStorage.queryOpts) {
//            //first time

//            oQueryOpts.currentLimit = 20;
//            oQueryOpts.currentOffset = 20;
//            oQueryOpts.currentPage = 1;
//            oQueryOpts.currentFilter = '';
//            oQueryOpts.currentSort = 'displayName';
//            oQueryOpts.currentSortDirection = '';
//            //// -- end of the options //


//        }
//        else {

//            alert('there');
//            //update the scrolling

//            //get the object from local storage
//            var retrievedString = localStorage.getItem('queryOpts');
//            oQueryOpts = JSON.parse(retrievedString);

//            //if we want to see it....
//            //console.log('retrieved Object: ', JSON.parse(oQueryOpts));

//            //update it
//            //oQueryOpts.currentPage = oQueryOpts.currentPage + 1;
//            // alert(oQueryOpts.currentPage + 'datahandler: I got it');
//        }
//        ////store it in local storage
//        //localStorage.setItem('queryOpts', JSON.stringify(oQueryOpts));

//        //  alert(oQueryOpts.currentPage + 'datahandler:  for here');
//    }
//    else {
//        //TODO:this device is not supported, we need local storage on the machine anyway!
//    }

//    console.log('...exiting BuildQueryObject...');
//    alert(oQueryOpts.currentPage);
//    return oQueryOpts;
//},
    /*************************************************************/
       


        ////get all child categories of 'path' from database
        //getContacts: function (callback) {

        //    db.transaction(
        //        function (transaction) {
        //            transaction.executeSql(
        //                'SELECT * FROM contacts', [],
        //                function (transaction, result) {
        //                    var contacts = [], i, row;
        //                    for (i = 0; i < result.rows.length; i += 1) {
        //                        row = result.rows.item(i);
        //                        contacts.push(row);
        //                    }
        //                    callback(contacts);
        //                }, errorHandler);
        //        }
        //    );
        //},


        // Delete table from database
        dropTable: function () {
            db.transaction(
                function (transaction) {
                    transaction.executeSql("DROP TABLE contacts", [], null, errorHandler);
                }
            );
        },


        //isTableExists
        isTableExists: function (tableName, callback) {
            alert('isTableExists - searching for: ' + tableName);
            db.transaction(
                function (transaction) {
                    transaction.executeSql('SELECT * FROM ' + tableName, [], function (tx, resultSet) {
                        if (resultSet.rows.length <= 0) {
                            callback(false, 'no data');
                        } else {
                            callback(true, '');
                        }
                    }, function (transaction, err) {
                        errorHandler(transaction, err)
                        callback(false, err.message);
                    }); //transaction.executeSql
                });
        }//END isTableExists



    };
}());

